import Vue from 'vue'
import Vuex, { Store } from 'vuex'
import cart from '@/store/shop'

Vue.use(Vuex)

const cartPlugin = store => {
  // 当 store 初始化后调用  subcsribe(订阅)
  // 每次mutation发生改变后执行下面的函数
  store.subscribe((mutation, state) => {
    // console.log({ mutation, state })
    // 判断触发的mutation的类型是否是cart模块的
    if (mutation.type.includes('cart')) {
      // 只要提交了cart类型的mutation就重新存localStorage
      localStorage.setItem('cart', JSON.stringify(state.cart.cart))
    }
  })
}

const store = new Store({
  modules: {
    cart
  },
  plugins: [cartPlugin]
})

export default store
